import Taro, { navigateTo } from "@tarojs/taro";
import createPromise from "../create-promise";
import { store } from "@/store";

function createFetchHandler(config?: Record<string, unknown>) {
  return async function (options: any): Promise<any> {
    const promise = createPromise();
    const data = options.data ?? ((options.params as any) || {});
    const {
      user: { auth },
    } = store.getState();
    let _headers;
    if (auth.token) {
      _headers = {
        Authorization: JSON.stringify({ token: auth.token }),
      };
    }

    let url;
    if (options.url.startsWith("http")) {
      url = options?.url;
    } else {
      url = options.prefix
        ? options.prefix + options.url
        : process.env.SERVER_HOST + options?.url || "";
    }
    Taro.request({
      ...options,
      url,
      method: (options.method as any) || "GET",
      data,
      headers: {
        ...options.headers,
        ..._headers,
      },
      timeout: 60000,
      ...config,
      success(res) {
        if (typeof res === "string" || res?.data?.code === "0") {
          promise.resolve(res?.data);
        } else if (res?.data?.code === "8003") {
          Taro.showToast({
            title: res?.data.msg || "登录状态失效，请重新登录",
            icon: "none",
            duration: 2000,
          });
          setTimeout(() => {
            navigateTo({
              url: "/sub_common/pages/auth/index",
            });
          }, 2000);
        } else {
          promise.reject(res?.data);
        }
      },
      fail(error) {
        promise.reject(error);
      },
    });
    return await promise;
  };
}

export const request = createFetchHandler();

export default createFetchHandler;
